package com.yy.rabbitmq.service.impl;

import com.yy.rabbitmq.config.MessageConfig;
import com.yy.rabbitmq.service.ISmsService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SmsServiceImpl implements ISmsService, RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendEmailMessage(String message) {
        this.rabbitTemplate.setConfirmCallback(this);
        this.rabbitTemplate.setReturnCallback(this);
        //这里设置超时时间需要配合插件，百度rabbitmq 延迟插件
        this.rabbitTemplate.convertAndSend(MessageConfig.SMS_TOPIC_EXCHANGE,"sms.email",message,message1 -> {
            message1.getMessageProperties().setDelay(10000);
            return message1;
        });
    }

    @Override
    public void sendPhoneMessage(String message) {
        this.rabbitTemplate.setConfirmCallback(this);
        this.rabbitTemplate.setReturnCallback(this);
        this.rabbitTemplate.convertAndSend(MessageConfig.SMS_TOPIC_EXCHANGE,"sms.phone",message);
    }


    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String s) {
        if (ack) {
            System.out.println("消息发送到交换机成功");
        }else {
            System.out.println("消息发送到交换机失败的原因"+s);
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        String correlationId = message.getMessageProperties().getCorrelationId();
        System.out.println("一旦执行return就代表消息没有从交换机发送到队列，消息id为："+correlationId+",应答码"+replyCode+",原因："+replyText
        +",交换机名字为"+exchange+",routingKey为"+routingKey);
    }
}
